package top.healthylife.gateway.platform.baohu.api.util.baofoo;


import top.healthylife.basics.utils.exception.BusinessException;

import javax.net.ssl.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;


public class HttpClient {


	public static String sendRequest(String method, String urlstr, String  request) {
		HttpsURLConnection conn = null;
		OutputStream os = null;
		String retStr = null;
		try {

			TrustManager[] tm = {new X509TrustManager() {
				@Override
                public void checkClientTrusted(X509Certificate[] chain,
                        String authType) throws CertificateException {
                }
				@Override
                public void checkServerTrusted(X509Certificate[] chain,
                        String authType) throws CertificateException {
                }
				@Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
        }  };
			SSLContext sslContext = SSLContext.getInstance("TLSv1.1", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			URL url = new URL(urlstr);
			conn = (HttpsURLConnection) url.openConnection();
			conn.setSSLSocketFactory(ssf);
			conn.setConnectTimeout(5 * 1000);
			conn.setReadTimeout(60 * 1000);
			conn.setRequestMethod(method);
			conn.setDoOutput(true);
			conn.setRequestProperty("Content-Encoding", "UTF-8");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			os = conn.getOutputStream();
			// 判断传入请求数据的类型，目前只处理String
			if (request instanceof String) {
				// 请求来的数据需要先做url编码
				os.write(request.getBytes("UTF-8"));
			}
			os.flush();
			int rCode = conn.getResponseCode();
			System.out.println("http状态码为"+rCode);
			if (HttpURLConnection.HTTP_OK == rCode) {
				if (null != conn.getInputStream()) {
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					int i = -1;
					try {
						while ((i = conn.getInputStream().read()) != -1) {
							baos.write(i);
						}
					} catch (IOException e) {
						throw new IOException(e);
					}
					retStr = baos.toString("UTF-8");

				}
			} else {
				throw new BusinessException("请求报错返回的http码"+rCode);
			}
		} catch (Exception e) {
			System.out.println(e);
		} finally {
			try {
				os.close();
				conn.disconnect();
			} catch (Exception e) {
				os = null;
				conn = null;
			}
		}
		return retStr;
	}
}

